#!/bin/bash
#
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Create a core on disk
# arguments are: corename configdir

set -e

echo "Executing $0" "$@"

if [[ "${VERBOSE:-}" == "yes" ]]; then
    set -x
fi

CORE=${1:-gettingstarted}
CONFIG_SOURCE="${2:-}"
if [[ -z "$CONFIG_SOURCE" ]]; then
    DEFAULT_CONFIGS=(_default data_driven_schema_configs)
    for config_dir in "${DEFAULT_CONFIGS[@]}"; do
        config_dir="/opt/solr/server/solr/configsets/$config_dir"
        if [ -d "$config_dir" ]; then
           CONFIG_SOURCE="$config_dir"
           break
        fi
    done
    if [[ -z $CONFIG_SOURCE ]]; then
        echo "Cannot find default config"
        exit 1
    fi
fi

coresdir=/var/solr/data

coredir="$coresdir/$CORE"
if [[ ! -d $coredir ]]; then
    cp -r "$CONFIG_SOURCE/" "$coredir"
    touch "$coredir/core.properties"
    echo "Created $CORE"
else
    echo "Core $CORE already exists"
fi
